package com.icehand.payment.pay.wechat.js;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.PayChannelEnum;
import com.icehand.common.enums.SignTypeEnum;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.NotifyWrapper;
import com.icehand.payment.model.PayWrapper;
import com.icehand.payment.pay.wechat.BaseWechatPay;
import com.icehand.payment.pay.wechat.WeChatPaymentSignatureUtils;
import com.icehand.payment.pay.wechat.WeChatPaymentUnifiedOrderRequest;
import com.icehand.payment.pay.wechat.WeChatPaymentUnifiedOrderResponse;
import com.icehand.wechat.js.WechatJsHelper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.client.RestTemplate;

/**
 * @author icehand
 */
@Slf4j
public class WechatJsPay extends BaseWechatPay {
    private static final PayChannelEnum CHANNEL = PayChannelEnum.WECHAT_H5_PAY;
    private final WechatJsHelper wechatJsHelper;

    public WechatJsPay(RestTemplate restTemplate, XmlMapper xmlMapper, WechatJsHelper wechatJsHelper,
                       PayNotifyRecordMapper payNotifyRecordMapper) {
        super(restTemplate, xmlMapper, payNotifyRecordMapper);
        this.wechatJsHelper = wechatJsHelper;
    }


    @Override
    protected boolean isWechatPay(PayChannelEnum payChannelEnum) {
        return CHANNEL.equals(payChannelEnum);
    }

    @Override
    protected WeChatPaymentUnifiedOrderRequest createUnifiedOrder(PayWrapper payWrapper) {
        String openid = wechatJsHelper.getWeChatOpenId(payWrapper.getConfig().getString("appId"),
                payWrapper.getExtendMap().get("uid") == null ? null :  Long.valueOf(payWrapper.getExtendMap().get("uid")),
                payWrapper.getConfig().getString("secret"),payWrapper.getExtendMap().get("code"));
        return super.createUnifiedOrder(payWrapper)
                .setTrade_type("JSAPI")
                .setOpenid(openid);
    }

    @Override
    protected void doAfter(PayWrapper payWrapper, WeChatPaymentUnifiedOrderResponse response) {
        if(payWrapper.getBizResult().isSuccess()){
            WeChatJsPayment weChatJsPayment = new WeChatJsPayment()
                    .setAppId(response.getAppId())
                    .setNonceStr(WeChatPaymentSignatureUtils.generateNonceStr())
                    .setTimestamp(new DateTime().getMillis()/1000 + "")
                    .setSignType(SignTypeEnum.MD5.getType())
                    .setPackageStr("prepay_id="+response.getPrepayId());
            weChatJsPayment.createSign(payWrapper.getConfig().getString(CommonConstants.K_SECRET));
            payWrapper.putData(weChatJsPayment);
        }
    }

    @Override
    public void payNotify(NotifyWrapper notifyWrapper) {

    }

    @Override
    public PayChannelEnum getChannel() {
        return CHANNEL;
    }
}
